﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Reviewer.Entities.Services;
using Reviewer.Business;
using Reviewer.Entities;
using System.Drawing.Imaging;

public partial class CMSV2_Controls_GameScreenshots : System.Web.UI.UserControl
{
    private string selectedFileName;

    public Guid GameId
    {
        get;
        set;
    }

    private GameScreenshot[] screenshots;

    public Format[] Formats { get; set; }

    public void Refresh()
    {
        using (IGameService service = ServiceFactory.GameService)
        {
            this.screenshots = service.GetAssociatedScreenshots(this.GameId);

            uiRepScreenshotImages.DataSource = screenshots.GroupBy(t => t.FileName).Select(t => t.FirstOrDefault()).OrderBy(t => t.FileName);
            uiRepScreenshotImages.DataBind();

            uiLitFilename.Text = "Vælg fil";
            foreach (ListItem item in uiCblFormats.Items)
            {
                //if (Formats != null)
                //{
                //    item.Enabled = Array.Exists<Format>(Formats, t => t.Id.Equals(int.Parse(item.Value)));
                //    if (uiCblNewImageFormats.Items.FindByValue(item.Value) != null)
                //    {
                //        uiCblNewImageFormats.Items.FindByValue(item.Value).Enabled = item.Enabled;
                //    }
                //}
                item.Selected = false;
            }
            uiBtnSaveScreenshot.Enabled = false;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            using (IMetadataService<Format> service = ServiceFactory.GetMetadataService<Format>())
            {
                uiCblNewImageFormats.DataSource = service.GetAll().OrderBy(t => t.Name); ;
                uiCblNewImageFormats.DataBind();

                uiCblFormats.DataSource = service.GetAll().OrderBy(t => t.Name);
                uiCblFormats.DataBind();
            }
        }
    }

    protected void uiRepScreenshotImages_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            GameScreenshot currentDataItem = e.Item.DataItem as GameScreenshot;
            Image img = e.Item.FindControl("uiImgScreenshotImage") as Image;
            img.ImageUrl = ResolveUrl("~/screenshots/" + currentDataItem.FileName);

            Literal file = e.Item.FindControl("uiLitScreenshotImageFile") as Literal;
            file.Text = currentDataItem.FileName;
        }
    }

    public void uiImageUploader_OnImageTransformationComplte(object sender, System.Drawing.Image transformedImage)
    {
        using (IGameAdminService gaService = ServiceFactory.GameAdminService)
        using (IMetadataService<Format> service = ServiceFactory.GetMetadataService<Format>())
        {
            Format[] selectedgameFormats = service.GetAll().Where(f => uiCblNewImageFormats.Items.FindByValue(f.Id.ToString()).Selected).ToArray();
            if (selectedgameFormats.Length > 0)
            {
                string imageFileName = Guid.NewGuid().ToString() + ".png";
                string imageLocation = MapPath(ResolveUrl("~/screenshots/" + imageFileName));
                transformedImage.Save(imageLocation, ImageFormat.Png);

                List<GameScreenshot> newScreenshot = new List<GameScreenshot>();
                foreach (Format selectedFormat in selectedgameFormats)
                {
                    GameScreenshot shot = new GameScreenshot();
                    shot.FileName = imageFileName;
                    shot.Format = selectedFormat.Id;
                    shot.GameId = GameId;
                    newScreenshot.Add(shot);

                    this.selectedFileName = imageFileName;
                }
                gaService.AddAssociatedScreenshots(newScreenshot.ToArray());
            }
        }
        this.Refresh();
        SetSelectedFile();
    }

    private void SetSelectedFile()
    {
        foreach (RepeaterItem item in this.uiRepScreenshotImages.Items)
        {
            Image img = item.FindControl("uiImgScreenshotImage") as Image;
            string filename = img.ImageUrl.Substring(img.ImageUrl.LastIndexOf("/") + 1);

            if (filename.ToUpperInvariant().Equals(this.selectedFileName.ToUpperInvariant(), StringComparison.Ordinal))
            {
                uiLbSelectImage_Click(item.FindControl("uiLbSelectImage"), new EventArgs());
            }
        }
    }

    protected void uiBtnDelete_Click(object sender, EventArgs e)
    {
        Image img = (sender as Button).Parent.FindControl("uiImgScreenshotImage") as Image;
        string filename = img.ImageUrl.Substring(img.ImageUrl.LastIndexOf("/") + 1);
        using (IGameAdminService adminService = ServiceFactory.GameAdminService)
        {
            adminService.DeleteAssociatedScreenshotsBy(filename);
            System.IO.File.Delete(MapPath(img.ImageUrl));
        }
        this.Refresh();
    }

    public void uiLbSelectImage_Click(object sender, EventArgs e)
    {
        foreach (RepeaterItem item in this.uiRepScreenshotImages.Items)
        {
            (item.FindControl("uiLbSelectImage") as LinkButton).CssClass = String.Empty;
        }
        (sender as LinkButton).CssClass = "selectedImage";

        Page.ClientScript.RegisterStartupScript(this.GetType(), "selectedImage-Focus", (sender as LinkButton).ClientID + ".scrollIntoView(false);", true);

        string filename = ((sender as LinkButton).Parent.FindControl("uiLitScreenshotImageFile") as Literal).Text;
        uiLitFilename.Text = filename;

        foreach (ListItem item in this.uiCblFormats.Items)
        {
            item.Selected = false;
        }

        this.screenshots = ServiceFactory.GameService.GetAssociatedScreenshots(this.GameId);

        foreach (GameScreenshot shot in (screenshots.Where(t => t.FileName.Equals(filename, StringComparison.OrdinalIgnoreCase))))
        {
            uiCblFormats.Items.FindByValue(shot.Format.ToString()).Selected = true;
        }

        uiBtnSaveScreenshot.Enabled = true;
    }

    public void uiBtnSaveScreenshot_Click(object sender, EventArgs e)
    {
        List<int> selectedFormats = new List<int>();
        foreach (ListItem item in uiCblFormats.Items)
        {
            if (item.Selected)
                selectedFormats.Add(int.Parse(item.Value));
        }

        if (selectedFormats.Count == 0)
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "AtLeastOneFormat", "alert('Husk mindst 1 format');", true);
            return;
        }

        this.selectedFileName = this.uiLitFilename.Text;

        using (IGameAdminService adminService = ServiceFactory.GameAdminService)
        {

            this.screenshots = ServiceFactory.GameService.GetAssociatedScreenshots(this.GameId);
            string filename = uiLitFilename.Text;

            GameScreenshot[] shots = ServiceFactory.GameService.GetAssociatedScreenshots(this.GameId).Where(t => t.FileName.Equals(filename, StringComparison.OrdinalIgnoreCase)).ToArray();
            foreach (GameScreenshot shot in shots)
            {
                if (!selectedFormats.Contains(shot.Format))
                {
                    adminService.DeleteAssociatedScreenshotBy(shot.Id);
                }
                else
                {
                    selectedFormats.Remove(shot.Format);
                }
            }

            foreach (int format in selectedFormats)
            {
                GameScreenshot newShot = new GameScreenshot();
                newShot.Format = format;
                newShot.FileName = filename;
                newShot.GameId = this.GameId;
                adminService.AddAssociatedScreenshot(newShot);
            }
        }

        this.Refresh();
        SetSelectedFile();
    }
}
